/**
 * Author: DingBaoyong
 * Desc: 3D地图js
 */
$(function() {
    hg.Map.initMap("container", {
        animation: false,  //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        homeButton: false, //是否显示起始按钮控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        fullscreenButton: false, //是否显示全屏按钮控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false,  //是否显示点击要素之后显示的信息
        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
            url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk="+ TIDITU_TK,
            layer: "tdtBasicLayer",
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",
            show: false
        })
        /*imageryProvider: new Cesium.UrlTemplateImageryProvider({
            url:'http://mt3.google.cn/vt/lyrs=s@762&x={x}&y={y}&z={z}',
            tilingScheme: new Cesium.WebMercatorTilingScheme(),
            minimumLevel: 1,
            maximumLevel: 20
        })*/
    });

    //选中隐患点
    hg.chooseYhd = function(yhdId){
        hg.Map.moveToYhd(yhdId);
    }
});

(function(Global) {
    Global.Ding = function() {
    };

    Global.Ding.prototype.Util = {
        getLocation : function(successHandler, errorhandler) {
            let geolocation = window.navigator.geolocation
            if (geolocation) {
                let options = {
                    enableHighAccuracy : true,
                };
                geolocation.getCurrentPosition(successHandler, errorhandler,
                    options);
            } else {
                errorhandler && errorhandler();
            }
        }
    };

    Global.Ding.Map = {
        MapType : {
            TMAP : 0,
            BMAP : 1
        },
        TMAP : function() {
            let viewer;
            let markers=[], labels=[], controls=[], projectInfos=[];
            function addMapTypeSelector(container) {
                let html = [];
                html.push("<select id=\"mapTypeSelect\">");
                html.push("<option value=\"TMAP_NORMAL_MAP\">地图</option>");
                html.push("<option value=\"TMAP_SATELLITE_MAP\">卫星</option>");
                html.push("<option value=\"TMAP_HYBRID_MAP\">卫星混合</option>");
                html.push("<option value=\"TMAP_TERRAIN_MAP\">地形</option>");
                html.push("<option value=\"TMAP_TERRAIN_HYBRID_MAP\">地形混合</option>");
                html.push("</select>");
                let dom = document.createElement("div");
                dom.innerHTML = html.join(" ");
                if (typeof container == "string")
                    container = $("#" + container);
                container[0].appendChild(dom);
                setMapTypeSelectorEvent($(dom));
                return dom;
            }

            function setMapTypeSelectorEvent(selector) {
                return selector.on("change", function(obj) {
                    map.setMapType(eval(obj.target.value))
                });
            }

            //创建3D地图
            function createMap(container, options) {
                Cesium.Ion.defaultAccessToken = CESIUM_ACCESSTOKEN;
                viewer = new Cesium.Viewer(container, options);
                //去除CESIUM图标
                viewer._cesiumWidget._creditContainer.style.display = "none";
                //全球影像中文注记服务
                /*addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
                    url: "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk="+ TIDITU_TK,
                    layer: "tdtAnnoLayer",
                    style: "default",
                    format: "image/jpeg",
                    tileMatrixSetID: "GoogleMapsCompatible",
                    show: false
                }));*/
                /*let terrain = new Cesium.createWorldTerrain({
                    requestWaterMask: true,
                    requestVertexNormals: true
                });
                viewer.terrainProvider = terrain;//加入世界地形图*/
                //设置相机的最小高度
                //viewer.scene.screenSpaceCameraController.minimumZoomDistance = 500;
            }
            //添加3D地图影像
            function addImageryProvider(imageryProvider) {
                viewer.imageryLayers.addImageryProvider(imageryProvider);
            }

            function setMapEvent(event, callback){
                TEvent.addListener(map, event, callback);
            }

            function setNavigationControl() {
                addControl(new TNavigationControl({
                    type : "TMAP_NAVIGATION_CONTROL_LARGE", // 缩放平移控件的显示类型
                    anchor : "TMAP_ANCHOR_TOP_LEFT" // 缩放平移控件显示的位置
                }));
            }

            function setMapTypeSelector(container) {
//                let mapTypeStyle = addMapTypeSelector(container);
//
//                let mapTyleControl = new THtmlElementControl(mapTypeStyle);
//                mapTyleControl.setRight(10);
//                mapTyleControl.setTop(10);
                let mapTypeControl = new TMapTypeControl();
                addControl(mapTypeControl);
            }

            function addControl(control){
                map.addControl(control);
                controls.push(control);
            }

            function addOverLay(overLay){
                map.addOverLay(overLay);
            }
            function addLabel(label){
                map.addOverLay(label);
                labels.push(label);
            }

            function setMapControls(container) {
                setNavigationControl();
                setMapTypeSelector(container);
            }

            function showAlarm(id, alarm){
                let idx,marker;
                for(let idx in markers){
                    marker = marker[idx];
                    if(marker.projectId == id){
                        marker.setIconImage(alarm?"./images/warning48.png":"./images/point16.png")
                        break;
                    }
                }
            }

            //加载3D模型
            /*function createModel(url, info) {
                let lng = info.lng;
                let lat = info.lat;
                let height = info.height;
                let position = Cesium.Cartesian3.fromDegrees(lng, lat, height);
                let heading = Cesium.Math.toRadians(90);
                let pitch = 0;
                let roll = 0;
                let hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
                let orientation = Cesium.Transforms.headingPitchRollQuaternion(
                    position,
                    hpr
                );

                let entity = viewer.entities.add({
                    data: info,
                    name: url,
                    position: position,
                    orientation: orientation,
                    model: {
                        uri: url,
                        minimumPixelSize: 128,
                        maximumScale: 20000,
                    }
                });
            }*/

            return {
                init: function(container, options) {
                    createMap(container, options);
                    //setMapControls(container);
                },
                createMaker: function(id, yhdName, yhdInfo, lng, lat, callbacks){

                    let marker = new TMarker(this.createLngLat(lng, lat));
                    marker.yhdName = yhdName;
                    marker.setTitle(yhdInfo);
                    marker.setIcon(this.createMarkerGetGreenIcon());
                    marker.yhdId = id;
                    callbacks = callbacks || {};
                    $.each(callbacks, function(event, callback){
                        TEvent.addListener(marker, event, callback);
                    });
                    markers.push(marker)
                    return marker;
                },
                createLngLat:function(long,lati){
                    return new TLngLat(long,lati);
                },
                createMarkerClusterer:function(config){
                    return new TMarkerClusterer(map,config);
                },
                createMarkerGetGreenIcon: function(){
                    return new TIcon("./images/point16.png", new TSize(37,33));
                },
                createMarkerGetYellowIcon:function(){
                    return new TIcon("https://map.tianditu.com/images/maptool/point15.png",new TSize(37,33));
                },
                createMarkerGetRedIcon:function(){
                    return new TIcon("https://map.tianditu.com/images/maptool/point14.png",new TSize(37,33));
                },
                addLableControl: function(text, lng, lat){
                    let position = this.createLngLat(lng, lat);
                    let label = new TLabel({text: text, position: position});
                    addLabel(label);
                    return label;
                },
                //添加点标记
                addMarker: function(type, iconUrl, info){
                    let labelName, near, nearValue, far, farValue;
                    let lng = info.lng;
                    let lat = info.lat;
                    let height = info.height;
                    info.type = type;
                    info.iconUrl = iconUrl;
                    let position = Cesium.Cartesian3.fromDegrees(lng, lat, height);
                    if(type == 1){
                        labelName = info.yhdName;
                        near = 1.5e3;
                        nearValue = 0;
                        far = 1.5e5;
                        farValue = 1;
                    }else if(type == 2 || type == 3){
                        labelName = info.deviceName;
                        near = 1e3;
                        nearValue = 1;
                        far = 1.5e3;
                        farValue = 0;
                    }
                    if(lng && lat){
                        if(type == 1 || type == 2){
                            viewer.entities.add({
                                data: info,
                                position: position,
                                billboard: {
                                    // 图像地址，URI或Canvas的属性
                                    image: iconUrl,
                                    // 设置颜色和透明度
                                    color: Cesium.Color.WHITE.withAlpha(1),
                                    // 高度（以像素为单位）
                                    height: 40,
                                    // 宽度（以像素为单位）
                                    width: 30,
                                    // 逆时针旋转
                                    rotation: 0,
                                    // 大小是否以米为单位
                                    sizeInMeters: false,
                                    // 相对于坐标的垂直位置
                                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                                    // 相对于坐标的水平位置
                                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                                    // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
                                    pixelOffset: new Cesium.Cartesian2(0, 0),
                                    // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
                                    //scale: 1.0,
                                    //scaleByDistance 设置屏幕像素缩放比，150米的时候放大一倍，150000米的时候，缩放到0
                                    scaleByDistance: new Cesium.NearFarScalar(near, nearValue, far, farValue),
                                    // 是否显示
                                    show: true
                                },
                                label : {
                                    text : labelName,
                                    font : '14pt monospace',
                                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                                    outlineWidth : 2,
                                    verticalOrigin : Cesium.VerticalOrigin.TOP,
                                    pixelOffset : new Cesium.Cartesian2(0, 10),
                                    scaleByDistance: new Cesium.NearFarScalar(near, nearValue, far, farValue),
                                    // 是否显示
                                    show: true
                                }
                            });
                        }else if(type == 3){
                            let heading = Cesium.Math.toRadians(info.heading);
                            let pitch = Cesium.Math.toRadians(info.pitch);
                            let roll = Cesium.Math.toRadians(info.roll);
                            let hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
                            let orientation = Cesium.Transforms.headingPitchRollQuaternion(
                                position,
                                hpr
                            );
                            viewer.entities.add({
                                data: info,
                                name: iconUrl,
                                position: position,
                                orientation: orientation,
                                model: {
                                    uri: iconUrl,
                                    minimumPixelSize: 128,
                                    maximumScale: 20000,
                                    distanceDisplayCondition: {
                                        near: 0,
                                        far: far
                                    },
                                    scale: 2
                                }
                            });
                        }
                    }
                    //viewer.flyTo(viewer.entities);
                },
                updateMarkerInfo: function(data){
                    let entities = viewer.entities.values;
                    $.each(entities, function(index, entity){
                        let info = entity._data;
                        if(info.type != 3){
                            //将所有监测点图标重置为默认图标
                            entity.billboard.image = info.iconUrl;
                            for(let i in data){
                                let alarmLog = data[i];
                                if(info.type == 1){
                                    if(info.yhdId == alarmLog.yhdId){
                                        entity.billboard.image = "images/warning48.png";
                                    }
                                }else if(info.type == 2){
                                    if(info.monitorDeviceCode == alarmLog.monitorDeviceCode && info.id == alarmLog.deviceId){
                                        entity.billboard.image = "images/warning32_40.png";
                                    }
                                }
                            }
                        }
                    })
                },
                //添加图标左键点击事件
                addMarkerLeftClickEvent: function(){
                    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
                    handler.setInputAction(function(click) {
                        let pick = viewer.scene.pick(click.position);
                        //弹出的信息提示框dom名字
                        let digDivName;
                        //选中某模型   pick选中的对象
                        if (!(pick && pick.id)) {
                            $("#yhdInfoDiv").css("display", "none");
                            $("#deviceInfoDiv").css("display", "none");
                        } else {
                            let data = pick.id._data;
                            let type = data.type;
                            if (type == 1) {
                                digDivName = "yhdInfoDiv";
                            } else if (type == 2) {
                                digDivName = "deviceInfoDiv";
                                let yhdId = data.yhdId;
                                let monitorDeviceCode = data.monitorDeviceCode;
                                let deviceId = data.id;
                                $("#deviceInfo_data").attr("href", "./monitorData/index.html?yhdId="+ yhdId + "&monitorDeviceCode=" + monitorDeviceCode + "&deviceId=" + deviceId);
                                $("#deviceInfo_alarm").attr("href", "./alarmManage/index.html?yhdId="+ yhdId + "&monitorDeviceCode=" + monitorDeviceCode);
                            }
                            fillContent(type, data);
                            $("#" + digDivName).show();
                            let cartesian2 = new Cesium.Cartesian2(click.position.x, click.position.y);
                            let x = cartesian2.x - ($("#" + digDivName).width()) / 2;
                            let y = cartesian2.y - ($("#" + digDivName).height()) + 64;
                            $("#" + digDivName).css("transform", 'translate3d(' + x + 'px, ' + y + 'px, 0)');
                        }
                    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
                },
                initialized:function(){
                    this.createMarkerClusterer({markers:markers});
                    if(markers.length>0){
                        map.panTo(markers[0].getLngLat(),14);
                    }
                },
                moveToYhd:function(yhdId){
                    let entities = viewer.entities.values;
                    let entityArr = [];
                    let options = {
                        offset : {
                            heading : Cesium.Math.toRadians(0),
                            pitch : Cesium.Math.toRadians(-90),
                            range : 1.5e5
                        }
                    };
                    $.each(entities, function(index, entity){
                        let info = entity._data;
                        if(info.type == 1 && info.id == yhdId){
                            entityArr.push(entity);
                        }
                    })
                    viewer.flyTo(entityArr, options);
                },
                showAlarm: function(data){
                    let mi, marker, yi, yhdAlarm;
                    for(mi in markers){
                        marker = markers[mi];
                        marker.setIconImage("./images/point16.png");
                        for(yi in data){
                            yhdAlarm = data[yi]
                            if(marker.yhdId == yhdAlarm.yhdId){
                                if(yhdAlarm.count){
                                    marker.setIconImage("./images/warning48.png");
                                    break;
                                }
                            }
                        }
                    }
                },
                addYhdInfo:function(data){
                    let yhdType = getValueByIndex("yhdType", data.yhdType);
                    let jcStage = getValueByIndex("jcStage", data.jcStage);
                    let monitorLevel = getValueByIndex("monitorLevel", data.monitorLevel);
                    let yf = getValueByIndex("yf", data.yf);
                    let wxdx = getValueByIndex("wxdx", data.wxdx);
                    let yhdInfo = "隐患点名称: " + data.yhdName + "\n" +
                        "隐患点类型: " + yhdType + "\n" +
                        "监测阶段: " + jcStage + "\n" +
                        "监测级别: " + monitorLevel + "\n" +
                        "诱发因素: " + yf + "\n" +
                        "威胁对象: " + wxdx + "\n";
                    return yhdInfo;
                }
            };
        }
    };

    Global.Ding.prototype.Map = {

        setMapType : function(mapType) {
            this.mapType = mapType;
        },
        setMap : function(map) {
            this.map = map;
        },
        getMap : function() {
            return this.map;
        },
        initMap : function(container, options) {
            let _this = this;
            if (typeof container == "object") {
                options = container;
                container = undefined;
            }
            container = container || "map";
            options = options || {};
            //生成地图处理器
            _this.mapHandler = new Ding.Map.TMAP();
            _this.mapHandler.init(container, options);
        },
        //显示隐患点数据
        showYhdData: function (iconUrl, data){
            let _this = this, mapHandler = _this.mapHandler;
            //图标类型
            let type = 1;
            $.each(data, function(index, item){
                mapHandler.addMarker(type, iconUrl, item);
            });
            mapHandler.addMarkerLeftClickEvent();
        },
        //显示监测点数据
        showModelData: function (data){
            let _this = this, mapHandler = _this.mapHandler;
            //图标类型
            let type = 3;
            $.each(data, function(index, item){
                mapHandler.addMarker(type, "model/"+ item.modelUrl, item);
            });
        },
        //显示监测点数据
        showDeviceInfo: function (iconUrl, data){
            let _this = this, mapHandler = _this.mapHandler;
            //图标类型
            let type = 2;
            $.each(data, function(index, item){
                mapHandler.addMarker(type, iconUrl, item);
            });
            mapHandler.addMarkerLeftClickEvent();
        },
        //更新图标
        updateMarkerInfo: function(data){
            let _this = this, mapHandler = _this.mapHandler;
            mapHandler.updateMarkerInfo(data);
        },
        moveToYhd: function(yhdId, zoom){
            let _this = this, mapHandler = _this.mapHandler;
            mapHandler.moveToYhd(yhdId, zoom);
        },
        showAlarm: function(data){
            let _this = this, mapHandler = _this.mapHandler;
            mapHandler.showAlarm(data);
        }
    };

})(this);